﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace KDAcctAttach {

    public partial class FrmAttach : Form {

        public FrmAttach()
        {
            InitializeComponent();
        }

        private BindingSource bs = new BindingSource();
        private List<AcctItemModel> acctList;

        #region 启用/禁用界面

        private void EnBtn(bool s)
        {
            void eb()
            {
                tbxDir.Enabled = s;
                btnBrowser.Enabled = s;
                btnAttach.Enabled = s;
                dgvAcctList.Enabled = s;
            }
            if (InvokeRequired)
                Invoke(new MethodInvoker(() => eb()));
            else
                eb();
        }

        #endregion 启用/禁用界面

        #region 浏览

        private void BtnBrowser_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fd = new FolderBrowserDialog();
            if (!string.IsNullOrEmpty(tbxDir.Text))
                fd.SelectedPath = tbxDir.Text;
            if (fd.ShowDialog() != DialogResult.OK)
                return;
            tbxDir.Text = fd.SelectedPath;
            if (!tbxDir.Text.EndsWith(@"\"))
                tbxDir.Text += @"\";
            GenerateFileList();
        }

        #endregion 浏览

        #region 读取文件列表

        private async void GenerateFileList()
        {
            try
            {
                EnBtn(false);
                acctList.Clear();
                string path = tbxDir.Text;
                if (string.IsNullOrEmpty(path))
                    throw new Exception("必须选择路径");
                var err = await Task.Run(() =>
                {
                    try
                    {
                        var files = Directory.GetFiles(path, "*.mdf", SearchOption.AllDirectories)?.ToList();
                        var ldfFiles = Directory.GetFiles(path, "*.ldf", SearchOption.AllDirectories)?.ToList();
                        if (files is null)
                            return null;
                        if (files.Count < 1)
                            return null;
                        files.ForEach(file =>
                        {
                            AcctItemModel acct = new AcctItemModel();
                            string pattern = "";
                            FileInfo fi = new FileInfo(file);
                            if (fi.Name.ToLower().StartsWith("acctctl"))
                            {
                                // 账套管理库
                                pattern = @"[aA][cC][cC]\S+_";
                                var match = Regex.Match(fi.Name, pattern);
                                if (match.Groups.Count > 0)
                                {
                                    acct.AcctName = match.Groups[0].Value;
                                    acct.AcctName = acct.AcctName.Substring(0, acct.AcctName.Length - 1);
                                    acct.MDFName = file;
                                    // 日志文件
                                    acct.LDFName = ldfFiles.FirstOrDefault(p => p.Contains(acct.AcctName));
                                    if (string.IsNullOrEmpty(acct.LDFName))
                                        acct.ErrInfo = "未找到日志文件";
                                    else
                                        acct.ErrInfo = "";
                                    acctList.Add(acct);
                                }
                            }
                            else if (fi.Name.ToLower().StartsWith("ais"))
                            {
                                // 账套
                                pattern = @"[aA][iI][sS]\d+";
                                var match = Regex.Match(fi.Name, pattern);
                                if (match.Groups.Count > 0)
                                {
                                    // 账套名
                                    acct.AcctName = match.Groups[0].Value;
                                    // MDF文件名
                                    //pattern = acct.AcctName + @"\S*.[mM][dD][fF]";
                                    //match = Regex.Match(file, pattern);
                                    acct.MDFName = file;
                                    // 查找LDF
                                    acct.LDFName = ldfFiles.FirstOrDefault(p => p.Contains(acct.AcctName));
                                    if (string.IsNullOrEmpty(acct.LDFName))
                                        acct.ErrInfo = "未找到日志文件";
                                    else
                                        acct.ErrInfo = "";
                                    acctList.Add(acct);
                                }
                            }
                        });
                        return null;
                    }
                    catch (Exception ex)
                    {
                        return ex.Message;
                    }
                });
                if (!string.IsNullOrEmpty(err))
                    throw new Exception(err);
                bs.ResetBindings(false);
                //dgvAcctList.Refresh();
                EnBtn(true);
            }
            catch (Exception ex)
            {
                acctList.Clear();
                MessageBox.Show(ex.Message);
                EnBtn(true);
            }
        }

        #endregion 读取文件列表

        #region 窗口载入

        private void Form1_Shown(object sender, EventArgs e)
        {
            acctList = new List<AcctItemModel>();
            dgvAcctList.DataSource = bs;
            bs.DataSource = acctList;
        }

        #endregion 窗口载入

        #region 附加数据库

        private async void BtnAttach_Click(object sender, EventArgs e)
        {
            try
            {
                if (acctList.Count < 1)
                    throw new Exception("没有可附加的账套");
                EnBtn(false);
                var db = DB.Inst();
                int succCount = 0;
                int failCount = 0;
                var err = await Task.Run(() =>
                {
                    try
                    {
                        acctList.ForEach(acc =>
                        {
                            string sqlstr = $@"sp_attach_db @DBNAME='{acc.AcctName}',@FILENAME1='{acc.MDFName}',@FILENAME2='{acc.LDFName}';";
                            try
                            {
                                db.Ado.ExecuteCommand(sqlstr);
                                acc.ErrInfo = "";
                                succCount++;
                            }
                            catch (Exception ex)
                            {
                                acc.ErrInfo = ex.Message;
                                failCount++;
                            }
                        });
                        return null;
                    }
                    catch (Exception ex)
                    {
                        return ex.Message;
                    }
                });
                if (!string.IsNullOrEmpty(err))
                    throw new Exception(err);
                MessageBox.Show($"操作完成,成功{succCount}个,失败{failCount}");
                bs.ResetBindings(false);
                EnBtn(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                EnBtn(true);
            }
        }

        #endregion 附加数据库
    }
}